#include "ohos_init.h"
///////////////////
#include "cmsis_os2.h"
#include "iot_gpio.h"
#include <stdio.h>

static osMessageQueueId_t g_queue;
osThreadId_t task1, task2;
#define BUFFER_LEN 50

// 添加一个同步信号量，用于控制任务执行顺序
static osSemaphoreId_t sync_sem;
static volatile uint32_t msg_processed = 0;

void send_Entry(void *argument)
{
    uint32_t i = 0;
    osStatus_t ret = osOK;
    char abuf[] = "test is message x";
    uint32_t len = sizeof(abuf);

    // 等待一小段时间，确保接收任务已经开始等待消息
    osDelay(10);

    while (i < 5) {
        abuf[len - 2] = '0' + i;
        i++;
        len = sizeof(abuf);
        if (len > BUFFER_LEN) {
            printf("mess is too long \n");
            return;
        }
        ret = osMessageQueuePut(g_queue, abuf, 0, 0);
        if (ret != osOK) {
            printf("send message failure, error: %x\n", ret);
        } else {
            //printf("send message: %s\n", abuf);
        }
        
        // 等待接收任务处理完这条消息
        osSemaphoreAcquire(sync_sem, osWaitForever);
    }
    
    // 等待所有消息处理完毕
    osDelay(100);
    
    // 终止接收任务
    osThreadTerminate(task2);
    
    // 删除队列
    if (osMessageQueueDelete(g_queue) != osOK) {
        printf("delete queue failed!\n");
    } else {
        printf("delete the queue success!\n");
    }
    
    // 删除信号量
    osSemaphoreDelete(sync_sem);
}

void recv_Entry(void *argument)
{
    osStatus_t ret = osOK;
    char readBuf[BUFFER_LEN] = {0};
    uint8_t msgPrio = 0;

    while (1) {
        ret = osMessageQueueGet(g_queue, readBuf, &msgPrio, osWaitForever);
        if (ret != osOK) {
            printf("recv message failure, error: %x\n", ret);
            break;
        }

        printf("recv message: %s\n", readBuf);
        
        // 通知发送任务这条消息已处理
        osSemaphoreRelease(sync_sem);
        
        // 增加已处理消息计数
        msg_processed++;
    }
}

uint32_t Example_CreateTask(void)
{
    osStatus_t ret = osOK;
    osThreadAttr_t senderAttr, receiverAttr;
    osMessageQueueAttr_t queueAttr = {
        .name = "queue",
        .attr_bits = 0U,
        .cb_mem = NULL,
        .cb_size = 0U,
        .mq_mem = NULL,
        .mq_size = 0U
    };
    
    // 创建同步信号量
    sync_sem = osSemaphoreNew(1, 0, NULL);
    if (sync_sem == NULL) {
        printf("create semaphore failed\n");
        return osError;
    }

    /* 首先创建消息队列，确保队列在任务执行前就存在 */
    g_queue = osMessageQueueNew(5, BUFFER_LEN, &queueAttr);
    if (g_queue == NULL) {
        printf("create queue failure, error: %x\n", osError);
        osSemaphoreDelete(sync_sem);
        return osError;
    }
    
    printf("create the queue success!\n");

    /* 设置接收任务的属性 - 先创建接收任务 */
    receiverAttr.name = "recvQueue";
    receiverAttr.attr_bits = 0U;
    receiverAttr.cb_mem = NULL;
    receiverAttr.cb_size = 0U;
    receiverAttr.stack_mem = NULL;
    receiverAttr.stack_size = 4096; // 相当于LOSCFG_BASE_CORE_TSK_DEFAULT_STACK_SIZE
    receiverAttr.priority = osPriorityNormal2;  // 相当于优先级10 
    receiverAttr.tz_module = 0;
    receiverAttr.reserved = 0;

    /* 创建接收任务 */
    task2 = osThreadNew(recv_Entry, NULL, &receiverAttr);
    if (task2 == NULL) {
        printf("create task2 failed, error: %x\n", osError);
        osMessageQueueDelete(g_queue);
        osSemaphoreDelete(sync_sem);
        return osError;
    }

    /* 设置发送任务的属性 */
    senderAttr.name = "sendQueue";
    senderAttr.attr_bits = 0U;
    senderAttr.cb_mem = NULL;
    senderAttr.cb_size = 0U;
    senderAttr.stack_mem = NULL;
    senderAttr.stack_size = 4096; // 相当于LOSCFG_BASE_CORE_TSK_DEFAULT_STACK_SIZE
    senderAttr.priority = osPriorityNormal1;  // 相当于优先级9
    senderAttr.tz_module = 0;
    senderAttr.reserved = 0;

    /* 创建发送任务 */
    task1 = osThreadNew(send_Entry, NULL, &senderAttr);
    if (task1 == NULL) {
        printf("create task1 failed, error: %x\n", osError);
        osThreadTerminate(task2);
        osMessageQueueDelete(g_queue);
        osSemaphoreDelete(sync_sem);
        return osError;
    }

    return osOK;
}

APP_FEATURE_INIT(Example_CreateTask);
